package br.gov.serpro.curso.projeto.wishlist;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.ContactsContract.Data;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import br.serpro.curso.projeto.db.DBOpenHelper;

public class CadastroActivity extends Activity {

	private ImageView imgProduto;

	private static TextView local;

	private static int UPDATE_LATLNG;

	private static LocationManager locationManager;

	private static ProgressBar pbLocal;

	static int mProgressStatus = 0;

	private static Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {
			Log.i("TESTE", (String) msg.obj);
			pbLocal.setVisibility(View.GONE);
			local.setText((String) msg.obj);
			try {
				locationManager = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private final LocationListener listener = new LocationListener() {

		@Override
		public void onLocationChanged(Location location) {

			double latitude = location.getLatitude();
			double longitude = location.getLongitude();
			int maxResults = 1;

			Log.i("TESTE", latitude+" - "+longitude);
			
			String endereco = "";
			Geocoder gc = new Geocoder(CadastroActivity.this,
					Locale.getDefault());
			List<Address> addresses;

			try {
				addresses = gc.getFromLocation(latitude, longitude, maxResults);

				if (addresses.size() == 1) {
					endereco = addresses.get(0).getThoroughfare() + " Nº "
							+ addresses.get(0).getSubThoroughfare() + ". "
							+ addresses.get(0).getLocality() + ", "
							+ addresses.get(0).getAdminArea() + " - "
							+ addresses.get(0).getPostalCode() + ". "
							+ addresses.get(0).getCountryCode();
				}

			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			Message.obtain(mHandler, UPDATE_LATLNG, endereco).sendToTarget();
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cadastro);

		local = (TextView) findViewById(R.id.et_local_produto);

		pbLocal = (ProgressBar) findViewById(R.id.pb_local);
		new Thread(new Runnable() {
			public void run() {

				Looper.prepare();
				while (pbLocal.getVisibility() != View.GONE) {
					mProgressStatus++;
					new Handler().post(new Runnable() {
						public void run() {
							Log.i("TESTE", "progress: " + mProgressStatus);
							pbLocal.setProgress(mProgressStatus);
						}
					});
				}
				Looper.loop();
			}
		}).start();

		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// LocationProvider provider =
		// locationManager.getProvider(LocationManager.GPS_PROVIDER);

		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 10000, // 10-second interval.
				100, // 10 meters.
				listener);

		imgProduto = (ImageView) findViewById(R.id.img_produto);

		imgProduto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent takePictureIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(takePictureIntent, 0);
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();

		Cursor c = DBOpenHelper.queryCategorias();

		final int total = c.getCount();

		String categorias[] = new String[total];
		Log.i("CAD", "total: " + total);
		int i = 0;
		while (c.moveToNext()) {
			categorias[i] = c.getString(0);
			i++;
		}
		c.close();

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, categorias);

		AutoCompleteTextView actvCategoria = (AutoCompleteTextView) findViewById(R.id.et_categoria);
		actvCategoria.setAdapter(adapter);

		Cursor cursor = getContentResolver().query(Data.CONTENT_URI,
				new String[] { Data.DISPLAY_NAME },
				Data.DISPLAY_NAME + " is not null", null, null); // (Phone.LABEL
																	// +
																	// " ASC LIMIT 20")

		final int total_contato = cursor.getCount();
		String contatos[] = new String[total_contato];
		i = 0;
		while (cursor.moveToNext()) {
			//Log.i("LISTA", "CONTATO: " + cursor.getString(0));
			contatos[i] = cursor.getString(0);
			i++;
		}
		cursor.close();

		ArrayAdapter<String> adapterContatos = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, contatos);

		AutoCompleteTextView actvContato = (AutoCompleteTextView) findViewById(R.id.et_contato);
		actvContato.setAdapter(adapterContatos);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_cadastro, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		handleSmallCameraPhoto(data);
	}

	private void handleSmallCameraPhoto(Intent intent) {
		Bundle extras = intent.getExtras();
		Bitmap mImageBitmap = (Bitmap) extras.get("data");
		imgProduto.setImageBitmap(mImageBitmap);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_salvar:

			ContentValues cv = new ContentValues();
			EditText nome = (EditText) findViewById(R.id.et_nome_produto);
			EditText local = (EditText) findViewById(R.id.et_local_produto);

			AutoCompleteTextView categoria = (AutoCompleteTextView) findViewById(R.id.et_categoria);
			EditText contato = (EditText) findViewById(R.id.et_contato);
			EditText preco_minimo = (EditText) findViewById(R.id.et_preco_minimo);
			EditText preco_maximo = (EditText) findViewById(R.id.et_preco_maximo);
			CheckBox notificar = (CheckBox) findViewById(R.id.cb_notificar);

			cv.put("nome", nome.getText().toString());
			cv.put("local", local.getText().toString());
			cv.put("categoria", categoria.getText().toString());
			cv.put("contato", contato.getText().toString());
			cv.put("preco_minimo", preco_minimo.getText().toString());
			cv.put("preco_maximo", preco_maximo.getText().toString());

			if (notificar.isChecked())
				cv.put("notificar", 1);
			else
				cv.put("notificar", 0);

			if (WishlistApp.getConexao().insertOrThrow("item", null, cv) > -1) {
				Toast.makeText(CadastroActivity.this, "CADASTRO COM SUCESSO!",
						Toast.LENGTH_LONG).show();
				finish();
			} else
				Toast.makeText(CadastroActivity.this, "ERRO NO CADASTRO!",
						Toast.LENGTH_SHORT).show();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
